#!/usr/bin/env python
# -*- coding: utf-8 -*-
#  middleware.py
#  description

#  Created by zhouzongli633 on 2020/6/11 1:44 下午.
#  Copyright ©Intellectus All rights reserved.

import json
import datetime

from Common.logger import app_log
from Common.decorators import check_token

try:
    from django.utils.deprecation import MiddlewareMixin  # Django 1.10.x
except ImportError:
    MiddlewareMixin = object  # Django 1.4.x - Django 1.9.x


class SimpleMiddleware(MiddlewareMixin):
    # @check_token()
    def process_request(self, request):
        try:
            request.start_time = datetime.datetime.now()

            app_log.info("{}:{}".format(
                request.start_time.strftime('%Y-%m-%d %H:%M:%S.%f'), request.META["PATH_INFO"])
            )

            if request.method == "GET":
                app_log.info("request.GET:{}".format(request.GET))
            elif request.method == "POST":
                if "admin/upload_file" in request.path:
                    return None
                post_param = json.loads(request.body)
                app_log.info("request.POST:{}".format(post_param))

            return None
        except Exception as e:
            app_log.exception(e)

    def process_response(self, request, response):
        execute_time = datetime.datetime.now()
        app_log.info("{} execute_time:{}".format(
            execute_time.strftime('%Y-%m-%d %H:%M:%S.%f'),
            (execute_time - request.start_time)
        ))

        if "/api/admin/education_content/content/" in request.path:
            return response
        if "/api/admin/education_content/category" == request.path:
            return response

        response_json = json.loads(response.content)
        app_log.info("response:{}".format(response_json))
        app_log.info("========================================================")
        return response
